import dayjs from "dayjs";
import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import elForm from '../form.vue'
import { ElTree } from 'element-plus';
import { $t } from "@/plugins/i18n";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";

import { roleList, addRole, updateRole, delRole, getRole, saveAuth } from '@/utils/api/system/role'
import { getMenuTreeList } from '@/utils/api/system/menu'

export function useDept() {
    const { locale } = useTranslationLang(); // 获取语言
    let checkedKeys: any = []
    const form = reactive({
        name: "",
        status: null,
        pageNumber: 0,
        pageSize: 10,
        sortName: "createtime",
        sortType: 0
    });

    const formRef = ref();
    const menuRef = ref();
    const dataList = ref([]);
    const loading = ref(true);
    const { tagStyle } = usePublicHooks();
    const pagination = reactive<PaginationProps>({
        total: 0,
        pageSize: 10,
        currentPage: 1,
        background: true
    });

    const columns = ref<TableColumnList>([
        {
            label: $t('adminRole.roleName'),
            prop: "name",
            width: 150,
            align: "left",
            sortable: true
        },
        {
            label: $t('adminRole.status'),
            prop: "status",
            minWidth: 100,
            cellRenderer: ({ row, props }) => (
                <el-tag size={props.size} style={tagStyle.value(row.status)}>
                    {row.status === 1 ? $t('adminRole.enable') : $t('adminRole.disable')}
                </el-tag>
            )
        },
        {
            label: $t('adminRole.creationTime'),
            prop: "createtime",
            minWidth: 200,
            formatter: ({ createTime }) => dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
        },
        {
            label: $t('adminRole.modificationTime'),
            prop: "updatetime",
            minWidth: 200,
            formatter: ({ createTime }) => dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
        },
        {
            label: $t('adminRole.remarks'),
            prop: "note",
            minWidth: 200,
            align: "left"
        },
        {
            label: $t('adminRole.operation'),
            fixed: "right",
            width: locale.value === 'zh' ? 200 : 250,
            slot: "operation"
        }
    ])

    function tableReloading() {
        columns.value = [
            {
                label: $t('adminRole.roleName'),
                prop: "name",
                width: 150,
                align: "left",
                sortable: true
            },
            {
                label: $t('adminRole.status'),
                prop: "status",
                minWidth: 100,
                cellRenderer: ({ row, props }) => (
                    <el-tag size={props.size} style={tagStyle.value(row.status)}>
                        {row.status === 1 ? $t('adminRole.enable') : $t('adminRole.disable')}
                    </el-tag>
                )
            },
            {
                label: $t('adminRole.creationTime'),
                prop: "createtime",
                minWidth: 200,
                formatter: ({ createTime }) => dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
            },
            {
                label: $t('adminRole.modificationTime'),
                prop: "updatetime",
                minWidth: 200,
                formatter: ({ createTime }) => dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
            },
            {
                label: $t('adminRole.remarks'),
                prop: "note",
                minWidth: 200,
                align: "left"
            },
            {
                label: $t('adminRole.operation'),
                fixed: "right",
                width: locale.value === 'zh' ? 200 : 250,
                slot: "operation"
            }
        ]
    }

    async function onSearch() {
        // 设置loading状态为true
        loading.value = true;
        // 获取角色列表
        const { Content } = await roleList(form);
        // 将Content.Results赋值给newData
        let newData = Content.Results;
        // 将newData赋值给dataList
        dataList.value = newData;
        // 将Content.TotalCount赋值给pagination.total
        pagination.total = Content.TotalCount;
        // 将Content.PageSize赋值给pagination.pageSize
        pagination.pageSize = Content.PageSize;
        // 将Content.PageNumber + 1赋值给pagination.currentPage
        pagination.currentPage = Content.PageNumber + 1;

        // 设置一个定时器，500毫秒后将loading状态设置为false
        setTimeout(() => {
            loading.value = false;
        }, 500);
    }

    // 重置
    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }

    // 所有菜单节点数据
    function getMenuAllCheckedKeys(menu) {
        // 返回目前半选中的节点的 key 所组成的数组
        checkedKeys = menu.getHalfCheckedKeys();
        // 返回目前被选中的节点的 key 所组成的数组
        let halfCheckedKeys = menu.getCheckedKeys();

        // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);

        halfCheckedKeys.unshift(...checkedKeys);
        return halfCheckedKeys;
    }

    // 点击授权
    async function openEmpower(row?: FormItemProps) {
        // 获取全部菜单树
        const { Content } = await getMenuTreeList();
        // 获取角色的菜单树
        let { Content: { MenuIds } } = await getRole(row.id);
        // console.log('默认选中的节点=>', MenuIds);
        // console.log('需要过滤掉的半选节点=>', checkedKeys);
        MenuIds = MenuIds.filter(item => !checkedKeys.includes(item))
        // console.log('过滤之后=>', arr);

        // MenuIds.unshift(...checkedKeys);
        // 设置默认属性
        const defaultProps = {
            children: 'Children',
            label: 'Name',
        }

        // 打开添加对话框
        addDialog({
            title: $t('adminRole.authorization'), // 对话框标题
            width: "35%", // 对话框宽度
            draggable: true, // 是否可拖拽
            fullscreenIcon: true, // 是否显示全屏图标
            closeOnClickModal: false, // 点击遮罩层是否关闭对话框
            contentRenderer: () => h(ElTree, { // 对话框内容渲染函数
                //@ts-ignore
                data: Content, // 树形数据
                props: defaultProps, // 默认属性
                showCheckbox: true, // 是否显示复选框
                nodeKey: "Id", // 节点key
                emptyText: "加载中，请稍后", // 空数据时的文本
                ref: menuRef, // 引用
                defaultCheckedKeys: MenuIds // 默认选中的节点key
            }),
            beforeSure: (done, { options }) => { // 确认按钮点击前回调函数
                function chores() {
                    message(`修改权限成功`, { // 提示信息
                        type: "success" // 提示类型
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }

                let data = {
                    roleId: row.id,
                    menuIdList: getMenuAllCheckedKeys(menuRef.value)
                }

                saveAuth(data).then(res => {
                    console.log('data', data);

                    if (res.Code === 0) chores();
                })
            }
        })
    }

    function openDialog(title = "新增", row?: FormItemProps) {
        let newTitle = title === '新增' ? $t('adminRole.addRole') : $t('adminRole.editRole');
        addDialog({
            title: newTitle,
            props: {
                formInline: {
                    name: row?.name ?? "",
                    status: row?.status ?? 1,
                    note: row?.note ?? ""
                }
            },
            width: "35%",
            draggable: true,
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(elForm, { ref: formRef } as any),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;
                function chores() {
                    message(`您${title}了角色名称为${curData.name}的这条数据`, {
                        type: "success"
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }
                FormRef.validate(valid => {
                    if (valid) {
                        console.log("curData", curData);
                        // 表单规则校验通过
                        if (title === "新增") {
                            addRole(curData).then(res => {
                                if (res.Code === 0) chores();
                            })
                        } else {
                            let data = Object.assign(curData, { roleId: row.id })
                            updateRole(data).then(res => {
                                if (res.Code === 0) chores();
                            })
                        }
                    }
                });
            }
        })
    }

    // 删除
    function handleDelete(row) {
        ElMessageBox.confirm(
            `是否确认删除名称为${row.name}的数据项?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            delRole(row.id).then(res => {
                if (res.Code === 0) {
                    message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    function handleSizeChange(val: number) {
        form.pageSize = val
        onSearch()
    }

    function handleCurrentChange(val: number) {
        form.pageNumber = val - 1
        onSearch()
    }

    onMounted(() => {
        onSearch()
    })

    return {
        columns,
        loading,
        dataList,
        openDialog,
        handleDelete,
        form,
        onSearch,
        resetForm,
        pagination,
        handleSizeChange,
        handleCurrentChange,
        openEmpower,
        tableReloading
    }
}